import {login, getInfo, logout} from '@/api/login'
import {Message} from 'element-ui'
import {resetRouter} from '@/router'
import {getToken, setToken, removeToken} from '@/utils/auth'


const state = {
  token: getToken(), // 认证凭证
  userName: '',
  permissions: [],
  introduce: ''
}
const mutations = {
  SET_TOKEN(state, token) {
    state.token = token
  },
  DEL_TOKEN(state) {
    state.token = ''
    state.userName = ''
    state.permissions = ''
    state.introduce = ''
  },
  SET_PERMISSIONS(state, permissions) {
    state.permissions = permissions
  },
  SET_USERNAME(state, userName) {
    state.userName = userName
  },
  SET_INTRODUCE(state, introduce) {
    state.introduce = introduce
  }
}
const actions = {
  // 用户登录操作
  _login({commit}, formdatas) {
    return new Promise((resolve, reject) => {
      login(formdatas).then(res => {
        if (res.code === 0) {
          Message.success(res.message);
          setToken(res.data.Authorization);
          commit('SET_TOKEN', res.data.Authorization);
        }
        resolve(res);
      }).catch(error => {
        reject(error);
      })
    })
  },
  // 退出登录操作
  _logout({commit}) {
    return new Promise((resolve, reject) => {
      logout().then(res => {
        if (res.code === 0) {
          Message.success(res.message);
          commit('DEL_TOKEN');
          removeToken();
          resetRouter();
        }
        resolve(res.data)
      }).catch(error => {
        reject(error)
      })
    })
  },
  // 获取用户信息
  _getInfo({commit}) {
    return new Promise((resolve, reject) => {
      getInfo().then(res => {
        if (res.code === 0) {
          const username = res.data.username;
          const permissions = res.data.permissions;
          const introduce = res.data.introduce;

          commit('SET_PERMISSIONS', permissions);
          commit('SET_USERNAME', username);
          commit('SET_INTRODUCE', introduce);
        }
        resolve(res.data)
      }).catch(error => {
        reject(error)
      })
    })
  },
  // 清除session操作
  _clean({commit}) {
    return new Promise((resolve, reject) => {
      commit('DEL_TOKEN');
      removeToken();
      resetRouter();
      resolve();
    })
  }
}
export default {
  namespaced: true,
  state,
  mutations,
  actions
}
